package com.example.txtransaction;

import com.atomikos.jdbc.AtomikosDataSourceBean;
import com.mysql.cj.jdbc.MysqlXADataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.sql.DataSource;

@Configuration
@MapperScan(sqlSessionFactoryRef = "sqlSessionFactoryA",basePackages = "com.example.txtransaction.a")
public class DataSourceConfigA {

    @Bean(value = "dataSourceA")
    @ConfigurationProperties(prefix = "spring.a.datasource")
    public DataSource dataSourceA(){
        return DataSourceBuilder.create().build();
    }

    @Bean(value = "mysqlXADataSourceA")
    @ConfigurationProperties(prefix = "spring.a.datasource")
    public MysqlXADataSource mysqlXADataSourceA(){
        return new MysqlXADataSource();
    }

    @DependsOn(value = "mysqlXADataSourceA")
    @Bean(value = "dataSourceXA")
    public DataSource dataSourceXA(@Qualifier(value = "mysqlXADataSourceA") MysqlXADataSource mysqlXADataSourceA){
        AtomikosDataSourceBean atomikosDataSourceBean = new AtomikosDataSourceBean();
        atomikosDataSourceBean.setXaDataSource(mysqlXADataSourceA);
        atomikosDataSourceBean.setUniqueResourceName("dataSourceXA");
        return atomikosDataSourceBean;
    }

    @Primary
    @Bean(value = "sqlSessionFactoryA")
    public SqlSessionFactory sqlSessionFactoryA(@Qualifier(value = "dataSourceXA") DataSource dataSourceA) throws Exception {
        SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
        factory.setDataSource(dataSourceA);
        factory.setTypeAliasesPackage("com.example.txtransaction.entity");
        ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
        Resource[] mappers = new PathMatchingResourcePatternResolver().getResources("classpath*:/mapper/a/*.xml");
        factory.setMapperLocations(mappers);
//        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
//        configuration.setMapUnderscoreToCamelCase(true);
//        factory.setConfiguration(configuration);
        return factory.getObject();
    }


}
